package com.dba.example.gwt.client.views.impl;

import com.dba.example.gwt.client.beans.Company;
import com.dba.example.gwt.client.editors.CompanyEditor;
import com.dba.example.gwt.client.views.CompanyEditView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

public class CompanyEditViewImpl extends Composite implements CompanyEditView {

	interface DefaultUiBinder extends UiBinder<Widget, CompanyEditViewImpl> {}

	interface Driver extends SimpleBeanEditorDriver<Company, CompanyEditor> {}

	private static DefaultUiBinder uiBinder = GWT.create(DefaultUiBinder.class);
	
	private Presenter presenter;
	
	private Driver driver;
	
	@UiField
	SimplePanel contents;
	
	@UiField
	Button save;
	
	private CompanyEditor editor;

    public CompanyEditViewImpl() {
    	initWidget(uiBinder.createAndBindUi(this));
    	contents.add(new CompanyEditor());
    }

	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}
	
	@Override
	public void edit(Company company) {
		contents.clear();
		editor = new CompanyEditor();
		contents.add(editor);
		
		driver = GWT.create(Driver.class);
		driver.initialize(editor);
		driver.edit(company);
	}
	
	public boolean flush() {
		driver.flush();
		return driver.hasErrors();
	}
	
	@UiHandler("save")
	void saveClicked(ClickEvent event) {
		presenter.save();
	}
	
}
